package hust.ning;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;

@SuppressWarnings("serial")
public class LoginServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		
		String xiaoneiID= req.getParameter("xiaonei_id");
		
		resp.setContentType("text/plain;charset=UTF-8");
		resp.setHeader("Cache-Control","no-cache");
		JSONObject obj = new JSONObject();
			String uid;
			if (xiaoneiID==null)
				uid= ChatApp.getInstance().login();
			else 
				uid= ChatApp.getInstance().login(xiaoneiID);
			
			List<String> rst = ChatApp.getInstance().getChat(uid);//same as getNotification
			try {
				obj.put("sessionID", uid);
				if (uid.equals(ChatApp.getInstance().getSingleUser()))
					obj.put("state", "wait");
				else if (rst == null)
					obj.put("state", "disconnected");
				else {
					obj.put("state", "keep");
					obj.put("chat", rst);
					obj.put("stranger_id",ChatApp.getInstance().getStrangerID(uid));
				}
			} catch (JSONException e) {
				e.printStackTrace();
			} 
			
		resp.getWriter().print(obj.toString());
		
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}
}
